package io.xxx.mario.job;

import io.xxx.mario.task.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.InterruptableJob;
import org.quartz.JobExecutionContext;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadLocalRandom;

@Slf4j
@Component
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class TestJob implements InterruptableJob {

    @Autowired
    private TaskService taskService;

    private boolean interrupted;

    @Override
    public void interrupt() {
        this.interrupted = true;
    }

    @Override
    public void execute(JobExecutionContext context) {
        log.info("Running job on supervisor, job id ");
        if (ThreadLocalRandom.current().nextInt(3) == 1) {
            try {
                throw new Exception("Randomly generated test exception on supervisor");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        log.info("Completed job on supervisor, job id ");
//        for (int i = 0; i < 100; i++) {
//            if (!interrupted) {
//                System.out.println(context);
//                System.out.println("任务执行 >>> " + i);
//                if (ThreadLocalRandom.current().nextInt(1, 5) == 3) {
//                    throw new RuntimeException("任务运行异常");
//                }
//                try {
//                    TimeUnit.MILLISECONDS.sleep(500);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        }
    }
}
